package com.ruoyi.web.controller.social.contract;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Contract;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.ContractMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.service.ContractService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Author: ruohao
 * @Date: 2023/9/3
 **/
@RestController
@RequestMapping("/social/contract")
public class ContractController extends BaseController {
    @Resource
    private ContractService contractService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserPostMapper sysUserPostMapper;

    @Log(title = "合同列表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Contract contract) {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        List<Long> postIds = sysUserPostMapper.getUserPosts(SecurityUtils.getUserId());
        if (CollectionUtils.isEmpty(postIds)) {
            // 默认只能看到自己的数据
            contract.setCreator(userId);
            contract.setDept(null);
        } else if (postIds.stream().anyMatch(p -> p < 7)) {
            // 副主任以上能看到所有数据
            contract.setCreator(null);
            contract.setDept(null);
        } else if (postIds.stream().anyMatch(p -> p <= 8 && p >= 7)) {
            // 科长副科长只能看到自己科室的数据
            contract.setCreator(null);
            contract.setDept(sysUser.getDeptId());
        } else {
            // 其他人只能看到自己科室的自己的数据
            contract.setCreator(userId);
            contract.setDept(sysUser.getDeptId());
        }
        List<Contract> list = contractService.selectList(contract);
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        util.exportExcel(response, list, "合同列表");
    }

    @GetMapping("/list")
    public TableDataInfo list(Contract contract) {
//        Long userId = SecurityUtils.getUserId();
//        SysUser sysUser = sysUserMapper.selectUserById(userId);
//        if (sysUser == null) {
//            return getDataTable(Collections.emptyList());
//        }
//        List<Long> postIds = sysUserPostMapper.getUserPosts(SecurityUtils.getUserId());
//        if (CollectionUtils.isEmpty(postIds)) {
//            // 默认只能看到自己的数据
//            contract.setCreator(userId);
//            contract.setDept(null);
//        } else if (postIds.stream().anyMatch(p -> p < 7)) {
//            // 副主任以上能看到所有数据
//            contract.setCreator(null);
//            contract.setDept(null);
//        } else if (postIds.stream().anyMatch(p -> p <= 8 && p >= 7)) {
//            // 科长副科长只能看到自己科室的数据
//            contract.setCreator(null);
//            contract.setDept(sysUser.getDeptId());
//        } else {
//            // 其他人只能看到自己科室的自己的数据
//            contract.setCreator(userId);
//            contract.setDept(sysUser.getDeptId());
//        }
        startPage();
        List<Contract> list = contractService.selectList(contract);
        return getDataTable(list);
    }

    /**
     * 创建项目时获取合同列表
     *
     * @param contract
     * @return
     */
    @GetMapping("/listProgram")
    public TableDataInfo listProgram(Contract contract) {
//        Long userId = SecurityUtils.getUserId();
//        SysUser sysUser = sysUserMapper.selectUserById(userId);
//        if (sysUser == null) {
//            return getDataTable(Collections.emptyList());
//        }
//        List<Long> postIds = sysUserPostMapper.getUserPosts(SecurityUtils.getUserId());
//        if (CollectionUtils.isEmpty(postIds)) {
//            // 默认只能看到自己的数据
//            contract.setCreator(userId);
//            contract.setDept(null);
//        } else if (postIds.stream().anyMatch(p -> p < 7)) {
//            // 副主任以上能看到所有数据
//            contract.setCreator(null);
//            contract.setDept(null);
//        } else if (postIds.stream().anyMatch(p -> p <= 8 && p >= 7)) {
//            // 科长副科长只能看到自己科室的数据
//            contract.setCreator(null);
//            contract.setDept(sysUser.getDeptId());
//        } else {
//            // 其他人只能看到自己科室的自己的数据
//            contract.setCreator(userId);
//            contract.setDept(sysUser.getDeptId());
//        }
        List<Contract> list = contractService.selectList(contract);
        return getDataTable(list);
    }

    @Resource
    private ContractMapper contractMapper;

    @GetMapping("/listDaoQi")
    public TableDataInfo listDaoQi() {
        List<Contract> list = contractMapper.selectDaoQi();
        return getDataTable(list);
    }

    @GetMapping("/listAll")
    public TableDataInfo listAll() {
        List<Contract> list = contractService.selectList(new Contract());
        return getDataTable(list);
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(contractService.selectById(id));
    }

    @Log(title = "垃圾分类管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody Contract contract) {
        Long userId = SecurityUtils.getUserId();
        contract.setCreator(userId);
        contract.setDept(Optional.ofNullable(sysUserMapper.selectUserById(userId)).map(SysUser::getDeptId).orElse(null));
        contract.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = contractService.create(contract);
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "垃圾分类管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@Validated @RequestBody Contract contract) {
        contract.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = contractService.update(contract);
        Contract search = contractService.selectById(contract.getId());
        if (search == null || !search.getCreateBy().equals(contract.getUpdateBy())) {
            throw new BaseException("该单据由" + search.getCreateBy() + "创建，您无法修改");
        }
        if (result) {
            return success();
        }
        return error();
    }

    @Log(title = "垃圾分类管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult remove(@PathVariable Long id) {
        Contract search = contractService.selectById(id);
        if (search == null || !search.getCreateBy().equals(SecurityUtils.getLoginUser().getUser().getNickName())) {
            throw new BaseException("该单据由" + search.getCreateBy() + "创建，您无法删除");
        }
        return toAjax(contractService.deleteById(id));
    }
}
